package com.ruoyi.system.service.impl;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ScoreManagementMapper;
import com.ruoyi.system.domain.ScoreManagement;
import com.ruoyi.system.domain.ExamManagement;
import com.ruoyi.system.service.IScoreManagementService;
import com.ruoyi.system.service.IQualificationManagementService;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.Validator;
import java.util.stream.Collectors;

import com.ruoyi.system.domain.dto.StatisticsDTO;
import com.ruoyi.system.domain.dto.StatisticsDTO.PositionData;

/**
 * 四级联考成绩合格名单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-04-02
 */
@Service
public class ScoreManagementServiceImpl implements IScoreManagementService 
{
    private static final Logger log = LoggerFactory.getLogger(ScoreManagementServiceImpl.class);

    @Autowired
    private ScoreManagementMapper scoreManagementMapper;
    
    @Autowired
    protected Validator validator;
    
    @Autowired
    private IQualificationManagementService qualificationManagementService;

    /**
     * 查询四级联考成绩合格名单
     * 
     * @param id 四级联考成绩合格名单主键
     * @return 四级联考成绩合格名单
     */
    @Override
    public ScoreManagement selectScoreManagementById(Long id)
    {
        return scoreManagementMapper.selectScoreManagementById(id);
    }

    /**
     * 查询四级联考成绩合格名单列表
     * 
     * @param scoreManagement 四级联考成绩合格名单
     * @return 四级联考成绩合格名单
     */
    @Override
    public List<ScoreManagement> selectScoreManagementList(ScoreManagement scoreManagement)
    {
        return scoreManagementMapper.selectScoreManagementList(scoreManagement);
    }

    /**
     * 新增四级联考成绩合格名单
     * 
     * @param scoreManagement 四级联考成绩合格名单
     * @return 结果
     */
    @Override
    public int insertScoreManagement(ScoreManagement scoreManagement)
    {
        return scoreManagementMapper.insertScoreManagement(scoreManagement);
    }

    /**
     * 修改四级联考成绩合格名单
     * 
     * @param scoreManagement 四级联考成绩合格名单
     * @return 结果
     */
    @Override
    public int updateScoreManagement(ScoreManagement scoreManagement)
    {
        return scoreManagementMapper.updateScoreManagement(scoreManagement);
    }

    /**
     * 批量删除四级联考成绩合格名单
     * 
     * @param ids 需要删除的四级联考成绩合格名单主键
     * @return 结果
     */
    @Override
    public int deleteScoreManagementByIds(Long[] ids)
    {
        return scoreManagementMapper.deleteScoreManagementByIds(ids);
    }

    /**
     * 删除四级联考成绩合格名单信息
     * 
     * @param id 四级联考成绩合格名单主键
     * @return 结果
     */
    @Override
    public int deleteScoreManagementById(Long id)
    {
        return scoreManagementMapper.deleteScoreManagementById(id);
    }

    /**
     * 导入四级联考成绩合格名单数据
     * 
     * @param scoreList 成绩合格名单数据列表
     * @param updateSupport 是否更新支持，如果已存在，是否覆盖
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public String importScoreData(List<ScoreManagement> scoreList, boolean updateSupport, String operName)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        
        for (ScoreManagement score : scoreList)
        {
            try
            {
                // 验证是否存在相同的准考证号或身份证号
                ScoreManagement existScore = new ScoreManagement();
                if (StringUtils.isNotEmpty(score.getExamNumber()))
                {
                    existScore.setExamNumber(score.getExamNumber());
                }
                else if (StringUtils.isNotEmpty(score.getIdCard()))
                {
                    existScore.setIdCard(score.getIdCard());
                }
                else
                {
                    throw new ServiceException("导入数据中准考证号和身份证号不能同时为空");
                }
                
                List<ScoreManagement> existList = scoreManagementMapper.selectScoreManagementList(existScore);
                
                if (StringUtils.isNull(existList) || existList.size() == 0)
                {
                    // 计算总成绩，如果需要的话
//                    if (score.getAdministrativeAptitudeScore() != null
//                            && score.getEssayScore() != null
//                            && score.getProfessionalSubjectScore() != null)
//                    {
//                        // 计算总成绩，此处仅为示例，根据实际需要调整计算方式
//                        score.setTotalScore(
//                            score.getAdministrativeAptitudeScore()
//                            .add(score.getEssayScore())
//                            .add(score.getProfessionalSubjectScore())
//                        );
//                    }
                    
                    // 如果不存在，执行插入操作
                    scoreManagementMapper.insertScoreManagement(score);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + score.getExamNumber() + " 导入成功");
                }
                else if (updateSupport)
                {
                    // 如果存在且允许更新
                    score.setId(existList.get(0).getId()); // 设置ID，确保更新正确的记录
                    
                    // 计算总成绩，如果需要的话
//                    if (score.getAdministrativeAptitudeScore() != null
//                            && score.getEssayScore() != null
//                            && score.getProfessionalSubjectScore() != null)
//                    {
//                        // 计算总成绩，此处仅为示例，根据实际需要调整计算方式
//                        score.setTotalScore(
//                            score.getAdministrativeAptitudeScore()
//                            .add(score.getEssayScore())
//                            .add(score.getProfessionalSubjectScore())
//                        );
//                    }
                    
                    scoreManagementMapper.updateScoreManagement(score);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、准考证号 " + score.getExamNumber() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、准考证号 " + score.getExamNumber() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、准考证号 " + score.getExamNumber() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
    
    /**
     * 从考试成绩数据生成并插入合格名单
     * 
     * @param examList 符合条件的考试成绩数据列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional
    public int insertQualifiedScoreListFromExam(List<ExamManagement> examList, String operName)
    {
        if (StringUtils.isNull(examList) || examList.size() == 0)
        {
            throw new ServiceException("合格考生数据不能为空！");
        }
        
        int successNum = 0;
        
        // 先清空现有合格名单数据
        ScoreManagement clearCriteria = new ScoreManagement();
        List<ScoreManagement> existingList = scoreManagementMapper.selectScoreManagementList(clearCriteria);
        if (existingList != null && existingList.size() > 0)
        {
            Long[] ids = new Long[existingList.size()];
            for (int i = 0; i < existingList.size(); i++)
            {
                ids[i] = existingList.get(i).getId();
            }
            scoreManagementMapper.deleteScoreManagementByIds(ids);
        }
        
        // 对考生按报考单位和职位分组
        java.util.Map<String, List<ExamManagement>> groupedExams = new java.util.HashMap<>();
        
        for (ExamManagement exam : examList) {
            // 生成分组键：报考单位+报考职位
            String groupKey = exam.getAppliedUnit() + "_" + exam.getAppliedPosition();
            
            if (!groupedExams.containsKey(groupKey)) {
                groupedExams.put(groupKey, new java.util.ArrayList<>());
            }
            
            groupedExams.get(groupKey).add(exam);
        }
        
        // 遍历分组，根据是否增加专业技能测试进行排序，并直接插入数据库
        for (String groupKey : groupedExams.keySet()) {
            List<ExamManagement> groupExams = groupedExams.get(groupKey);
            
            // 判断此组考生是否需要专业技能测试
            boolean needSkillTest = false;
            if (groupExams.size() > 0 && groupExams.get(0) != null) {
                needSkillTest = "是".equals(groupExams.get(0).getHasProfessionalSkillTest());
            }
            
            // 根据不同条件排序
            if (needSkillTest) {
                // 按专业技能测试成绩排序
                groupExams.sort((a, b) -> {
                    if (a.getProfessionalSkillTestScore() == null && b.getProfessionalSkillTestScore() == null) {
                        return 0;
                    }
                    if (a.getProfessionalSkillTestScore() == null) {
                        return 1;
                    }
                    if (b.getProfessionalSkillTestScore() == null) {
                        return -1;
                    }
                    return b.getProfessionalSkillTestScore().compareTo(a.getProfessionalSkillTestScore());
                });
            } else {
                // 按总成绩排序
                groupExams.sort((a, b) -> {
                    if (a.getTotalScore() == null && b.getTotalScore() == null) {
                        return 0;
                    }
                    if (a.getTotalScore() == null) {
                        return 1;
                    }
                    if (b.getTotalScore() == null) {
                        return -1;
                    }
                    return b.getTotalScore().compareTo(a.getTotalScore());
                });
            }
            
            // 重新设置排名
            for (int i = 0; i < groupExams.size(); i++) {
                groupExams.get(i).setRanking(Long.valueOf(i + 1));
            }
            
            // 直接处理当前分组，插入合格名单
            for (ExamManagement exam : groupExams) {
                try {
                    // 创建合格名单对象
                    ScoreManagement score = new ScoreManagement();
                    
                    // 复制考生信息
                    score.setCandidateId(exam.getCandidateId());
                    score.setName(exam.getName());
                    score.setGender(exam.getGender());
                    score.setIdCard(exam.getIdCard());
                    score.setExamNumber(exam.getExamNumber());
                    score.setAdministrativeAptitudeScore(exam.getAdministrativeAptitudeScore());
                    score.setEssayScore(exam.getEssayScore());
                    score.setProfessionalSubjectScore(exam.getProfessionalSubjectScore());
                    score.setTotalScore(exam.getTotalScore());
                    score.setProfessionalSkillTestScore(exam.getProfessionalSkillTestScore());
                    score.setAppliedUnit(exam.getAppliedUnit());
                    score.setAppliedPosition(exam.getAppliedPosition());
                    score.setRecruitmentNumber(exam.getRecruitmentNumber());
                    score.setInterviewRatio(exam.getInterviewRatio());
                    score.setRanking(exam.getRanking());  // 使用重新排序后的排名
                    score.setGraduationSchool(exam.getGraduationSchool());
                    score.setHasProfessionalSkillTest(exam.getHasProfessionalSkillTest());
                    score.setPositionCategory(exam.getPositionCategory());
                    score.setIsAlternate(exam.getIsAlternate());
                    score.setQualificationReviewResult(exam.getQualificationReviewResult());
                    score.setIdentityVerificationResult(exam.getIdentityVerificationResult());
                    score.setPhysicalTestResult(exam.getPhysicalTestResult());
                    score.setLeibie(exam.getLeibie());
//                    score.setFinalResult("通过");  // 默认为通过
                    
                    // 执行插入操作
                    scoreManagementMapper.insertScoreManagement(score);
                    successNum++;
                } catch (Exception e) {
                    log.error("插入合格名单失败，准考证号：" + exam.getExamNumber(), e);
                }
            }
        }
        
        return successNum;
    }

    /**
     * 生成资格审查名单
     * 根据招考人数及面试比例筛选考生
     * 
     * @param operName 操作用户
     * @return 资格审查人数
     */
    @Override
    @Transactional
    public int generateQualificationList(String operName)
    {
        // 查询所有成绩合格名单数据
        ScoreManagement criteria = new ScoreManagement();
        List<ScoreManagement> allScoreList = scoreManagementMapper.selectScoreManagementList(criteria);
        
        if (StringUtils.isNull(allScoreList) || allScoreList.size() == 0)
        {
            throw new ServiceException("成绩合格名单数据为空，无法生成资格审查名单！");
        }
        
        // 对考生按报考单位和职位分组
        java.util.Map<String, List<ScoreManagement>> groupedScores = new java.util.HashMap<>();
        
        for (ScoreManagement score : allScoreList) {
            // 生成分组键：报考单位+报考职位
            String groupKey = score.getAppliedUnit() + "_" + score.getAppliedPosition();
            
            if (!groupedScores.containsKey(groupKey)) {
                groupedScores.put(groupKey, new java.util.ArrayList<>());
            }
            
            groupedScores.get(groupKey).add(score);
        }
        
        // 筛选需要进入资格审查的考生
        List<ScoreManagement> qualifiedScoreList = new java.util.ArrayList<>();
        
        for (String groupKey : groupedScores.keySet()) {
            List<ScoreManagement> groupScores = groupedScores.get(groupKey);





            if (groupScores.size() > 0) {
                ScoreManagement firstScore = groupScores.get(0);
                
                // 获取当前职位的招考人数和面试比例
                Long recruitmentNumber = firstScore.getRecruitmentNumber();
                String interviewRatio = firstScore.getInterviewRatio();


                String hasProfessionalSkillTest = firstScore.getHasProfessionalSkillTest();
                if ("是".equals(hasProfessionalSkillTest)) {
                    // 如果有专业技能测试，则需要根据专业技能测试成绩排名，并按照排名进行筛选
                    groupScores.sort(Comparator.comparing(ScoreManagement::getProfessionalSkillTestScore).reversed());
                }

                if (recruitmentNumber != null && StringUtils.isNotEmpty(interviewRatio)) {
                    // 解析面试比例，如 "1:3" 表示面试人数为招考人数的3倍
                    int ratio = 3; // 默认为3倍
                    try {
                        String[] parts = interviewRatio.split(":");
                        if (parts.length == 2) {
                            ratio = Integer.parseInt(parts[1]);
                        }
                    } catch (Exception e) {
                        log.error("解析面试比例出错：" + interviewRatio, e);
                    }
                    
                    // 计算需要进入资格审查的人数
                    int requiredCount = recruitmentNumber.intValue() * ratio;
                    
                    // 筛选符合条件的考生（按排名顺序）
                    int addedCount = 0;
                    for (ScoreManagement score : groupScores) {
                        if (addedCount < requiredCount) {
                            if ("是".equals(hasProfessionalSkillTest)) {
                                score.setPaiming(String.valueOf(addedCount+1));
                            }
                            qualifiedScoreList.add(score);
                            addedCount++;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        
        // 将筛选出的考生插入到资格审查名单
        int qualifiedCount = 0;
        if (qualifiedScoreList.size() > 0) {
            qualifiedCount = qualificationManagementService.insertQualificationListFromScore(qualifiedScoreList, operName);
        }
        
        return qualifiedCount;
    }

    /**
     * 获取四级联考成绩合格名单统计数据
     * 
     * @return 统计数据
     */
    @Override
    public StatisticsDTO getScoreStatistics()
    {
        // 创建返回对象
        StatisticsDTO statisticsDTO = new StatisticsDTO();
        
        // 查询所有成绩合格名单数据
        List<ScoreManagement> scoreList = scoreManagementMapper.selectScoreManagementList(new ScoreManagement());
        
        // 总数
        int total = scoreList.size();
        statisticsDTO.setTotal(total);
        statisticsDTO.setPassed(total); // 合格名单默认都是通过的
        statisticsDTO.setFailed(0);
        
        // 职位分布统计
        Map<String, Integer> positionMap = new HashMap<>();
        
        for (ScoreManagement score : scoreList)
        {
            // 统计职位分布
            String position = score.getAppliedPosition();
            if (position != null && !position.isEmpty())
            {
                positionMap.put(position, positionMap.getOrDefault(position, 0) + 1);
            }
        }
        
        // 转换职位分布数据为前端所需格式
        List<PositionData> positionDataList = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : positionMap.entrySet())
        {
            positionDataList.add(new PositionData(entry.getKey(), entry.getValue()));
        }
        statisticsDTO.setPositionData(positionDataList);
        
        return statisticsDTO;
    }
}
